<?php
namespace app\mp\admin;
use app\common\service\Sku as SkuService;
use app\system\admin\Admin;
use think\Db;
use app\common\service\CostStatement as CostStatementService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\OrderMaterial as OrderMaterialService;

/**
 * 成本盈亏报表
 * @author huangyuan
 */
/*
 * 订单状态 1,未采购, 2,已采购,3,已裁床,4,已车缝,5,已后整,6,已出货,7,已完成,99,已废弃,999,MES废除
 * 1,未采购 caigou_status=0; 2,已采购 caigou_status =1 caichuang_status=0 3,已裁床 caichuang_status=1,chejian_status=0
 *	4,已车缝 chejian_status=1,tail_status=0 ,5,已后整  tail_status =1 real_shipment_status=0
 * 6,已出货  real_shipment_status =1  status=1, 7,已完成 status=2
 * */
class CostStatement extends Admin{

    public function index() {
        //cost_audit_status
        $export     = $this->request->param('export/d', 0);
        if ($this->request->isAjax() || $export>0) {
            $where = $data = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $factoryId = $this->request->param('factory_id/d', 0);
            $orderStatus = $this->request->param('order_status/s');
            $clientOrdernum = $this->request->param('client_ordernum/s');
            $sku = $this->request->param('sku/s');
            $createDateRange    = $this->request->param('create_date_range/s');
            $checkDateRange    = $this->request->param('update_date_range/s');

            $where[] = ['cost_audit_status', '=', 1];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            if ($createDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
                $where[] = ['o.create_time', 'between', [$startTime, $endTime+86399]];
            }
            if ($checkDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $checkDateRange));
                $where[] = ['o.cost_audit_time', 'between', [$startTime, $endTime+86399]];
            }

            if($sku) $where[] = ['o.sku', '=', $sku];
            if($clientOrdernum) $where[] = ['o.client_ordernum', '=', $clientOrdernum];
            if($factoryId) $where[] = ['o.factory_id', '=', $factoryId];
            //入库数统计
            /*$skuStock=db("sku_stock_log log")->join('order o', 'log.client_ordernum =o.client_ordernum','inner')
                ->field("sum(available_count) as available_checkin_count,
                sum(defective_count) as defective_checkin_count,FROM_UNIXTIME(tail_over_time,'%Y-%m') as month,log.factory_id,log.client_ordernum")
                ->where($where)->where('action_type','eq',1)->group("log.client_ordernum")->order('tail_over_time desc')->select();*/

            //实裁数 mes入仓数 补裁片数  ->where([['status','>','0']])
            $orderSizeData = db('order_size')
                ->field('order_id,sum(order_count) os_order_count,daohuo_count,sum(shicai_count) as shicai_count ,sum(store_count) as store_count,sum(sew_cut_count) as sew_cut_count')->group('order_id')
                ->buildSql();
            //订单加工费数据
            $orderProcessData=db("user_process up")->field("order_id,sum(up.quintity * up.process_price) as tot_process_price")
                ->group('order_id')
                //->join("order_progress_price")
                ->buildSql();
            //订单核价与补损表 cost_check 加工费，
            $costUseCheck=db("cost_check")->field("order_id,sum(up.quintity * up.process_price) as tot_process_price")->group('order_id')->buildSql();

            //case then
           /* ->field("sum(case when action_type = 1 then available_count else 0 end) as available_checkin_count,
                sum(case when action_type = 2 then available_count else 0 end) as available_checkout_count,
                sum(defective_count) as defective_checkin_count,FROM_UNIXTIME(tail_over_time,'%Y-%m') as month,log.factory_id")*/
            //核价类型 [0 => '加工费', 1 => '面辅料', 2 => '单件用量', 3 => '工艺染色',]; 补损类型 [10000 => '幅宽补损', 10001 => '公斤补损', 10002 => '米数补损',]

            $order = 'o.id desc';
            //列表的数据集
            $datalist=db("order o")
                ->join('sku sku', "sku.sku=o.sku", "left")
                ->join([$orderSizeData=> 'os'], 'o.id = os.order_id',"left")
                ->field("o.*,os.*,sku.pic,sku.ori_pic,sku.price,o.store_count as ostore_count")
                ->where($where)->page($page)->limit($limit)->order($order)->select();

            //入库数统计
            $orderStock=db("sku_stock_log log")->join('order o', 'log.client_ordernum =o.client_ordernum','inner')
                ->field("sum(available_count) as available_checkin_count,
                sum(defective_count) as defective_checkin_count,log.factory_id,log.client_ordernum,log.order_id")
                ->where([['log.order_id', 'in', array_column($datalist,'id')]])->where('action_type','eq',1)
                ->group("log.order_id")->select();
            $orderStockByOid=arrayByKey($orderStock,'order_id');
            //出库数统计
            $skuCheckOutStock=db("sku_stock_log log")->join('order o', 'log.out_ordernum =o.client_ordernum','inner')
                ->field("sum(available_count) as available_checkout_count,log.out_ordernum,log.client_ordernum,log.order_id")
                ->where([['log.order_id', 'in', array_column($datalist,'id')]])->where('action_type','eq',2)->group("log.out_ordernum")->order('tail_over_time desc')->select();
            $orderStockOutByOid=arrayByKey($skuCheckOutStock,'out_ordernum');


            foreach ($datalist as $key=>&$v){
                $orderStockByOid[$v['id']]['available_checkin_count']= empty( $orderStockByOid[$v['id']]['available_checkin_count'] ) ? 0 : $orderStockByOid[$v['id']]['available_checkin_count'];
                $orderStockByOid[$v['id']]['defective_checkin_count']= empty( $orderStockByOid[$v['id']]['defective_checkin_count'] ) ? 0 : $orderStockByOid[$v['id']]['defective_checkin_count'];

                $v["omlist"] = db('order_material om')
                    ->field("om.mid,om.order_id,om.tiaoshu,m.name as material_name,m.type as material_type")
                    ->join('material m', "om.material_id=m.id", 'left')
                    ->where([['om.order_id', 'in', $v['id']]])->select();

                $v['available_checkout_count']= empty( $orderStockOutByOid[$v['client_ordernum']]['available_checkout_count'] ) ? 0 : $orderStockOutByOid[$v['client_ordernum']]['available_checkout_count'];//出库其它单库存数
                $v['available_checkin_count']=$orderStockByOid[$v['id']]['available_checkin_count']+ $orderStockByOid[$v['id']]['defective_checkin_count']; //入库数
                $v['available_pre']=$v['shicai_count'] > 0? sprintf('%.4f',($v['store_count']+$v['available_checkin_count']-$v['available_checkout_count'])/($v['shicai_count']+$v['sew_cut_count'])) * 100: 0.00;//正品率
                $v['cut_diff']=$v['store_count']-($v['shicai_count']+$v['sew_cut_count']);//正品数
                $v['cut_diff_money']=sprintf('%.2f',$v['cut_diff'] * $v['price']);
                $v['cost_audit_time']=date("Y-m-d H:s",$v['cost_audit_time']);
                $v['omlistJson']=json_encode($v["omlist"]);
                $v['osJson']=json_encode($v);
            }

            $data['data'] = $datalist;
            $data['count'] = db("order o")->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        $factoryKV = getFactoryKV(false);
        $assign=[
            'today'=>date("y-m-d"),
            'factoryKV'=>[0 => '请选择'] + $factoryKV,
            'ProfitOrLoss'=>[0 => '请选择',1=>'无亏损',2=>'亏损'],
            'clientStatus' => config('mimo.client_status'),
        ];

        return $this->assign($assign)->fetch();
    }


    public function addConfig() {
        $num_type = $this->request->param('num_type/d');
        $process_cost = $this->request->param('process_cost/d');
        $process_status = $this->request->param('process_status/d');
        $confService = new CostStatementService();
        if ($this->request->isPost()) {
            $data = ['num_type' => $num_type, 'process_cost' => $process_cost, 'process_status' => $process_status];
            $info = $confService->addCostStatementConfig($data);
            if ($info == 1) {
               return $this->Json(1, '修改成功', $info);
            } else {
                return $this->Json(0, '修改失败', $info);
            }
        }
        $info = $confService->getCostStatementConfig();
        $assign = [
            'num_type' =>!empty($info['num_type']) ? $info['num_type'] : 1,
            'process_cost'=>!empty($info['process_cost'])? $info['process_cost'] : 0,
            'process_status'=>!empty($info['process_status']) ? $info['process_status'] : 0,
        ];
        return $this->assign($assign)->fetch();
    }

    //查询订单插入到成本盈亏表  0，新单，1，处理中，2已完成
    public function getOrderListByStatus($status = 2){
        if(!is_array($status)){
            $_status[] =  $status;
        }else{
            $_status = $status;
        }
        //store_count 入仓数
        $where[] = ['status','in',$_status];
        $field = 'id,factory_id,client_ordernum,sku_id,sku,quantity,caigou_status,
                   caichuang_status,chejian_status,tail_status,status,store_count,create_time,update_time';
        $page = 1;
        $limit = 10;
        $orderList = db('order')->field($field)->where($where)->page($page)->limit($limit)->order('update_time','asc')->select();
        if(empty($orderList)){
            return $this->Json(1, '数据为空');
        }
        $skuService = new SkuService();
        $costService = new CostStatementService();
        //处理完结果之后循环插入成本盈亏表
        //获取全部的sku信息
        $skuArr = array_unique(array_column($orderList, 'sku'));
        $skuField = 'ori_pic,pic,price';
        $skuMap = $skuService->getListBySkus($skuArr,$skuField);
        $config = $costService->getCostStatementConfig();
        foreach($orderList as $key=>$value){
            $order_size = $costService->orderSize($value['id']);
            $shicai_count = array_sum(array_column($order_size,'shicai_count'));//实裁数
            $pic = !empty($skuMap[$value['sku']]['pic']) ? $skuMap[$value['sku']]['pic'] : '';//图片
            $price = !empty($skuMap[$value['sku']]['price']) ? $skuMap[$value['sku']]['price'] : '';//加工费
            $accessories_price = 1;//面辅料
            $consumption_price = 1;//用量
            $process_price = 1;//二次工艺
            $make_lose = 1;//补损
            $genuine_loss = 1;//正品盈亏
            $order_status = 1;//订单状态。组合得出
            $is_profit = 1;//是否亏损、只要有一个是亏损的，就全部亏损
            $profit_type = $config['num_type'];//计算方式;配置表
            $process_cost_status = $config['process_cost_status']; //盈利计算方式;配置表
            $process_cost = $config['process_cost']; //盈利计算方式;配置表 百分比
            $data[$key]['order_id'] = $value['id'];
            $data[$key]['client_ordernum'] = $value['client_ordernum'];
            $data[$key]['sku'] = $value['sku'];
            $data[$key]['is_profit'] = $is_profit;
            $data[$key]['factory_id'] = $value['factory_id'];
            $data[$key]['shicai_count'] = $shicai_count;
            $data[$key]['create_time'] = $value['create_time'];
            $data[$key]['update_time'] = $value['update_time'];
            $data[$key]['pic'] = $pic;
            $data[$key]['price'] = $price;
            $data[$key]['accessories_price'] = $accessories_price;
            $data[$key]['consumption_price'] = $consumption_price;
            $data[$key]['process_price'] = $process_price;
            $data[$key]['make_lose'] = $make_lose;
            $data[$key]['genuine_loss'] = $genuine_loss;
            $data[$key]['order_status'] = $order_status;
            $data[$key]['profit_type'] = $profit_type;
            $data[$key]['process_cost_status'] = $process_cost_status;
            $data[$key]['process_cost'] = $process_cost;
        }
        var_dump($orderList);
    }
    //
}